package com.shsxt.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;

public class HibernateUtil {
    // ThreadLocal它提供了一种线程局部变量的机制。这种机制确保了每个线程都可以拥有自己的、独立的变量副本，这些变量对其他线程是不可见的
    private static ThreadLocal<Session> threadLocal = new ThreadLocal<>();
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;

    static {
        registry = new StandardServiceRegistryBuilder()
                .configure() //默认加载hibernate.cfg.xml
                .build();
        //从元信息获取Session工厂
        sessionFactory = new MetadataSources(registry)
                .buildMetadata()
                .buildSessionFactory();
    }
    public static Session getSession() {
        Session session = threadLocal.get();
        if (null ==session  || !session.isOpen()) {
            if (sessionFactory == null) {
                buildSessionFactory();}
            session = (null != sessionFactory) ? sessionFactory.openSession() : null;
            threadLocal.set(session);

        }

        return session;
    }

    private static void buildSessionFactory() {
        registry = new StandardServiceRegistryBuilder()
                .configure() //默认加载hibernate.cfg.xml
                .build();
        //从元信息获取Session工厂
        sessionFactory = new MetadataSources(registry)
                .buildMetadata()
                .buildSessionFactory();
    }

    public static void closeSession() {
        Session session = threadLocal.get();
        if (null != session&&session.isOpen()) {
            session.close();
        }
    }

}
